<template>
  <view
    class="comment-modal-mask"
    :class="{ visible: visible }"
    v-if="visible"
    @click="handleClose"
  >
    <view class="comment-modal-content" @click.stop>
      <view class="comment-header">
        <text>{{
          typeof localComments.count === "number"
            ? localComments.count + "条评论"
            : localComments.count
        }}</text>
        <text class="close-btn" @click="handleClose">×</text>
      </view>
      <scroll-view
        scroll-y
        class="comment-list"
        v-if="localComments.list && localComments.list.length > 0"
      >
        <view
          class="comment-item"
          v-for="(item, index) in localComments.list"
          :key="item.replyId"
        >
          <image :src="item.avatarUrl" class="user-head"></image>
          <view class="comment-body">
            <view class="user-info">
              <text class="user-nick">{{ item.authorName }}</text>
              <text class="author-tag" v-if="item.authorId === authorId"
                >作者</text
              >
              <text class="first-tag" v-if="item.firstReplay === 1">首评</text>
            </view>
            <text class="comment-text">{{ item.replayContent }}</text>
            <!-- 评论图片 -->
            <image 
              v-if="item.replayImgUrl" 
              :src="item.replayImgUrl" 
              class="comment-image"
              mode="widthFix"
              @click="previewImage(item.replayImgUrl)"
            ></image>
            <view class="comment-footer">
              <text class="time"
                >{{ formatDate(item.createTime) }}
                {{ item.ipRealAddress }}</text
              >
              <text class="reply-btn" @click="replyComment(item)">回复</text>
              <view class="like-btn" @click="likeComment(item)">
                <image
                  class="like-icon"
                  :src="item.isUp ? filledHeartIcon : outlineHeartIcon"
                ></image>
                <text class="like-count" v-if="item.upCount > 0">{{
                  item.upCount
                }}</text>
              </view>
            </view>

            <!-- 嵌套回复 -->
            <view class="reply-list" v-if="item.reply && item.reply.length > 0">
              <view
                class="reply-item"
                v-for="(reply, replyIndex) in item.reply"
                :key="reply.replyId"
              >
                <image :src="reply.avatarUrl" class="reply-head"></image>
                <view class="reply-body">
                  <view class="user-info">
                    <text class="user-nick">{{ reply.authorName }}</text>
                    <text class="author-tag" v-if="reply.authorId === authorId"
                      >作者</text
                    >
                  </view>
                  <text class="reply-text">
                    <text v-if="reply.parentAuthorName" class="reply-to"
                      >回复 {{ reply.parentAuthorName }}：</text
                    >
                    {{ reply.replayContent }}
                  </text>
                  <!-- 回复图片 -->
                  <image 
                    v-if="reply.replayImgUrl" 
                    :src="reply.replayImgUrl" 
                    class="reply-image"
                    mode="widthFix"
                    @click="previewImage(reply.replayImgUrl)"
                  ></image>
                  <view class="reply-footer">
                    <text class="time"
                      >{{ formatDate(reply.createTime) }}
                      {{ reply.ipRealAddress }}</text
                    >
                    <text class="reply-btn" @click="replyComment(item, reply)"
                      >回复</text
                    >
                    <view class="like-btn" @click.stop="likeComment(reply)">
                      <image
                        class="like-icon"
                        :src="reply.isUp ? filledHeartIcon : outlineHeartIcon"
                      ></image>
                      <text class="like-count" v-if="reply.upCount > 0">{{
                        reply.upCount
                      }}</text>
                    </view>
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
      <view class="empty-comment" v-else>
        <text class="empty-icon">💬</text>
        <text class="empty-text">还没有评论，快来抢沙发吧~</text>
      </view>
      <view class="comment-input-area">
        <!-- 选中的图片预览 -->
        <view class="selected-image-preview" v-if="selectedImage">
          <image :src="selectedImage" class="preview-image" mode="aspectFit"></image>
          <text class="remove-image-btn" @click="removeSelectedImage">×</text>
        </view>
        
        <view class="input-row">
          <input
            :always-embed="true"
            :adjust-position="true"
            cursor-spacing="30"
            type="text"
            v-model="newComment"
            :placeholder="inputPlaceholder"
            class="comment-input"
            @focus="isInputFocused = true"
            @blur="isInputFocused = false"
          />
          <image
            class="image-upload-btn"
            src="/static/image/sc.png"
            @click="chooseImage"
          ></image>
          <button class="send-btn" @click="sendComment">发送</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  name: "CommentModal",
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    comments: {
      type: Object,
      default: () => ({
        count: 0,
        list: [],
      }),
    },
    authorId: {
      type: [String, Number],
      default: "",
    },
  },
  data() {
    const filledHeartSvg = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="#fe2c55"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"></path></svg>`;
    const outlineHeartSvg = `<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="white"><path stroke-linecap="round" stroke-linejoin="round" d="M21 8.25c0-2.485-2.099-4.5-4.688-4.5-1.935 0-3.597 1.126-4.312 2.733-.715-1.607-2.377-2.733-4.313-2.733C5.1 3.75 3 5.765 3 8.25c0 7.22 9 12 9 12s9-4.78 9-12z" /></svg>`;
    return {
      newComment: "",
      replyTo: null,
      replyParent: null,
      isInputFocused: false,
      selectedImage: "", // 选中的图片预览URL
      uploadedImageId: "", // 上传后的图片ID
      uploadedImageUrl: "", // 上传后的图片URL
      filledHeartIcon:
        "data:image/svg+xml;charset=utf-8," +
        encodeURIComponent(filledHeartSvg),
      outlineHeartIcon:
        "data:image/svg+xml;charset=utf-8," +
        encodeURIComponent(outlineHeartSvg),
      // 添加本地副本
      localComments: {
        count: 0,
        list: [],
        noteId: "",
      },
    };
  },
  computed: {
    inputPlaceholder() {
      if (this.replyTo) {
        return `回复 ${this.replyTo.authorName}：`;
      }
      return "留下你的精彩评论吧";
    },
  },
  watch: {
    visible(val) {
      if (val) {
        // Delay focus to allow modal animation to complete
        setTimeout(() => {
          this.isInputFocused = true;
        }, 350);

        // 添加调试信息，查看接收到的评论数据
        console.log("CommentModal组件接收到数据:", this.comments);
        console.log("评论列表:", this.comments.list);

        // 当弹窗显示时，保存评论数据到本地副本
        if (this.comments && this.comments.list) {
          this.localComments = JSON.parse(JSON.stringify(this.comments));
          console.log("评论数据已保存到本地副本:", this.localComments);
        }
      } else {
        // When closing, ensure focus is false and reset state
        this.isInputFocused = false;
        this.resetReplyState();
      }
    },
    // 监听comments变化
    comments: {
      handler(newVal) {
        console.log("CommentModal组件comments数据变化:", newVal);
        // 更新本地副本
        if (newVal && newVal.list) {
          this.localComments = JSON.parse(JSON.stringify(newVal));
          // Ensure noteId is stored for refreshing comments
          if (newVal.noteId) {
            this.localComments.noteId = newVal.noteId;
          }
          console.log("评论数据更新到本地副本:", this.localComments);
        }
      },
      deep: true,
    },
  },
  mounted() {
    console.log("CommentModal挂载, 当前数据:", this.comments);
    // Store noteId for refreshing comments
    if (this.comments && this.comments.noteId) {
      this.localComments.noteId = this.comments.noteId;
    }
  },
  beforeDestroy() {},
  methods: {
    handleClose() {
      this.$emit("close");
    },

    resetReplyState() {
      this.newComment = "";
      this.replyTo = null;
      this.replyParent = null;
      this.selectedImage = "";
      this.uploadedImageId = "";
    },

    replyComment(parent, comment = null) {
      this.replyParent = parent;
      this.replyTo = comment || parent;
      // Refocus the input
      this.isInputFocused = false;
      setTimeout(() => {
        this.isInputFocused = true;
      }, 50);
    },

    likeComment(comment) {
      // 只发出事件，让父组件处理API调用
      console.log("发出点赞评论事件:", comment);
      this.$emit("like", comment);
    },

    // 预览图片
    previewImage(imageUrl) {
      uni.previewImage({
        urls: [imageUrl],
        current: imageUrl
      });
    },

    sendComment(e) {
      console.log(e);
      if (this.newComment.trim() === "" && !this.uploadedImageId) {
        uni.showToast({
          title: "请输入评论内容或选择图片",
          icon: "none",
        });
        return;
      }

      const commentData = {
        content: this.newComment,
        replyTo: this.replyTo ? this.replyTo.replyId : null,
        topParentId: this.replyParent ? this.replyParent.replyId : null,
        imageId: this.uploadedImageId, // 添加图片ID
        imageUrl: this.uploadedImageUrl, // 添加图片URL
      };

      // 发送评论事件到父组件
      this.$emit("send", commentData);

      // 重置状态
      this.resetReplyState();
    },

    formatDate(date) {
      if (!date) return "";
      return uni.app.formatDate(date);
    },

    // 选择图片
    chooseImage() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          const file = res.tempFiles[0];
          if (file.size > 2 * (1024 * 1024)) {
            uni.showToast({
              title: "图片尺寸过大，请选择小于2MB的图片",
              icon: "none"
            });
            return;
          }
          
          // 设置预览图片
          this.selectedImage = file.path;
          
          // 上传图片
          this.uploadImage(file);
        },
        fail: (err) => {
          console.log('选择图片失败:', err);
        }
      });
    },

    // 上传图片
    uploadImage(file) {
      uni.showLoading({
        title: '上传中...'
      });
      
      uni.uploadFile({
         url: 'https://www.yaozhuasocial.com/yaozhua/fe/aliImageUpload',
         filePath: file.path,
         name: 'file',
         formData: {
           fileSavePath: '/reply'
         },
        success: (uploadRes) => {
          try {
            const result = JSON.parse(uploadRes.data);
            if (result.code === 2000) {
              // this.uploadedImageId = result.data?.fileId || result.data?.fileId || '';
              this.uploadedImageUrl = result.data?.imageUrl || result.data?.imageUrl || '';
              uni.hideLoading();
              uni.showToast({
                title: '图片上传成功',
                icon: 'success'
              });
            } else {
              throw new Error(result.message || '上传失败');
            }
          } catch (e) {
            console.error('上传失败:', e);
            uni.hideLoading();
            uni.showToast({
              title: '图片上传失败，请重试',
              icon: 'none'
            });
            this.removeSelectedImage();
          }
        },
        fail: (err) => {
          console.error('上传请求失败:', err);
          uni.hideLoading();
          uni.showToast({
            title: '图片上传失败，请重试',
            icon: 'none'
          });
          this.removeSelectedImage();
        }
      });
    },

    // 移除选中的图片
    removeSelectedImage() {
      this.selectedImage = '';
      this.uploadedImageId = '';
      this.uploadedImageUrl = '';
    },
  },
};
</script>

<style scoped>
.comment-modal-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: flex-end;
  z-index: 100;
}

.comment-modal-content {
  width: 100%;
  height: 60%;
  background-color: #1a1a1a;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
  display: flex;
  flex-direction: column;
}

.comment-header {
  padding: 15px;
  text-align: center;
  position: relative;
  border-bottom: 1px solid #333;
  color: #fff;
}

.close-btn {
  position: absolute;
  right: 15px;
  top: 10px;
  font-size: 24px;
  color: #fff;
}

.comment-list {
  flex: 1;
  padding: 10px;
  color: #fff;
  height: 0;
}

.comment-item {
  display: flex;
  margin-bottom: 15px;
}

.user-head {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}

.comment-body {
  flex: 1;
}

.user-nick {
  color: #888;
  font-size: 14px;
  margin-right: 5px;
}

.comment-text {
  display: block;
  margin-top: 5px;
  font-size: 15px;
}

.comment-footer,
.reply-footer {
  display: flex;
  align-items: center;
  margin-top: 8px;
  font-size: 12px;
  color: #888;
}

.comment-input-area {
  padding: 15px;
  border-top: 1px solid #333;
}

.selected-image-preview {
  position: relative;
  margin-bottom: 10px;
  display: inline-block;
}

.preview-image {
  width: 100px;
  height: 100px;
  border-radius: 8px;
  background-color: #333;
}

.remove-image-btn {
  position: absolute;
  top: -8px;
  right: -8px;
  width: 24px;
  height: 24px;
  background-color: #fe2c55;
  color: #fff;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
}

.input-row {
  display: flex;
  align-items: center;
  gap: 10px;
}

.image-upload-btn {
  width: 40px;
  height: 40px;
  padding: 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: opacity 0.2s;
}

.image-upload-btn:hover {
  opacity: 0.8;
}

.comment-input {
  flex: 1;
  padding: 10px 15px;
  background-color: #333;
  color: #fff;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  min-height: 40px;
  line-height: 20px;
}

.send-btn {
  padding: 8px 20px;
  background-color: #fe2c55;
  color: #fff;
  border: none;
  border-radius: 20px;
  font-size: 14px;
  min-width: 60px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.author-tag {
  font-size: 10px;
  background-color: #ffeceb;
  color: #fa5f5a;
  border-radius: 10px;
  padding: 2px 6px;
  margin-left: 5px;
}

.first-tag {
  font-size: 10px;
  background-color: #f8f8f8;
  color: #666;
  border-radius: 10px;
  padding: 2px 6px;
  margin-left: 5px;
}

.reply-btn {
  margin-left: 10px;
  color: #fff;
  cursor: pointer;
}

.like-btn {
  display: flex;
  align-items: center;
  cursor: pointer;
  margin-left: 15px;
}

.like-icon {
  width: 16px;
  height: 16px;
}

.like-count {
  margin-left: 3px;
  font-size: 12px;
  color: #888;
}

.reply-list {
  margin-top: 10px;
  padding-left: 10px;
  border-left: 1px solid #333;
}

.reply-item {
  display: flex;
  margin-top: 10px;
}

.reply-head {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 8px;
}

.reply-body {
  flex: 1;
  overflow: hidden;
}

.reply-text {
  display: block;
  margin-top: 3px;
  font-size: 14px;
  word-break: break-all;
}

.reply-to {
  color: #888;
}

/* 评论图片样式 */
.comment-image {
  max-width: 200px;
  margin-top: 8px;
  border-radius: 8px;
  cursor: pointer;
}

/* 回复图片样式 */
.reply-image {
  max-width: 150px;
  margin-top: 6px;
  border-radius: 6px;
  cursor: pointer;
}

.empty-comment {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #666;
  height: 0;
}

.empty-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

.empty-text {
  font-size: 14px;
}
</style>
